package br.com.fogas.utils;

import java.io.File;
import java.io.IOException;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.webkit.MimeTypeMap;
import android.widget.ImageView;

public class CameraUtility {
	
	public void abrirFoto(Uri uri, Context context) {
		Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
		intent.setDataAndType(uri, getMimeTypeImage(uri));
		context.startActivity(intent);
	}
	
	public String getMimeTypeImage(Uri uri) {
		String mime = "*/*";
		MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
		if (mimeTypeMap.hasExtension(MimeTypeMap.getFileExtensionFromUrl(uri.toString())))
		    mime = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(uri.toString()));
		return mime;
	}
	
	public void carregaImagem(Uri uri, ImageView imageView, int width, int height) {
		Bitmap imagem = BitmapFactory.decodeFile(uri.getPath());
		Bitmap imagemReduzida = Bitmap.createScaledBitmap(imagem, width, height, false);
		imageView.setImageBitmap(imagemReduzida);
	}
	
	public File criarArquivoFoto(String nomeAlbum, String nomeFoto) throws IOException {  
		if(isExternalStorageWritable()) {
			File album = criarPastaAlbum(nomeAlbum);
			//String uniqueID = UUID.randomUUID().toString().replaceAll("-", "");
			File foto = new File(album.getPath() + File.separator + nomeFoto);
		    return foto;
		} else {
			throw new IOException("sem premissao de escrita");
		}
	}
	
	public File criarPastaAlbum(String nomeAlbum) throws IOException {  
		if(isExternalStorageWritable()) {
			//File file = new File(Environment.getExternalStorageDirectory(), folder_main);
		    File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), nomeAlbum);
			if (!file.exists()) {
				file.mkdirs();
			}
		    return file;
		} else {
			throw new IOException("sem premissao de escrita");
		}
	}

	
	/* Checks if external storage is available for read and write */
	public boolean isExternalStorageWritable() {
	    String state = Environment.getExternalStorageState();
	    if (Environment.MEDIA_MOUNTED.equals(state)) {
	        return true;
	    }
	    return false;
	}

	/* Checks if external storage is available to at least read */
	public boolean isExternalStorageReadable() {
	    String state = Environment.getExternalStorageState();
	    if (Environment.MEDIA_MOUNTED.equals(state) ||
	        Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
	        return true;
	    }
	    return false;
	}
}